<template>
  <div class="role-list-container">
    <el-card>
      <!-- 工具栏 -->
      <el-row :gutter="10" class="mb-4">
        <el-col :span="1.5">
          <el-button type="primary" @click="handleAddTag">新增角色</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
        </el-col>
      </el-row>

      <!-- 表格 -->
      <el-table
        :data="roles"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="roleId" label="角色编号" align="center"></el-table-column>
        <el-table-column prop="roleName" label="角色名称" align="center"></el-table-column>
        <el-table-column prop="roleDes" label="角色描述" align="center"></el-table-column>
        <el-table-column label="操作" width="240" align="center">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row.roleId)">修改</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row.roleId)">删除</el-button>
            <el-button size="small" type="warning" @click="openAssignPermissionDrawer(row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限抽屉 -->
    <el-drawer
      v-model="assignPermissionDrawerVisible"
      title="分配权限"
      direction="rtl"
      size="30%"
    >
      <div class="assign-permission-content">
        <el-tree
          :data="permissionTreeData"
          node-key="id"
          show-checkbox
          default-expand-all
          :props="defaultProps"
          ref="treeRef"
        />
        <div class="drawer-footer">
          <el-button @click="assignPermissionDrawerVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPermissions">保存权限</el-button>
        </div>
      </div>
    </el-drawer>
  </div>



<!-- 新增角色对话框  -->
  <el-dialog
    v-model="addDialogVisible"
    title="新增角色"
    width="500"
    
  >
    <!-- 新增角色页面-->
    <el-form v-model="addRole">
      <el-form-item label="角色名称">
        <el-input v-model="addRole.roleName" placeholder="请输入角色名称"/>
      </el-form-item>
      <el-form-item label="角色描述">
        <el-input v-model="addRole.roleDes" placeholder="请输入角色描述"/>
      </el-form-item>
    </el-form>


    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addRoleBtn">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>



  <!-- 修改角色对话框  -->
  <el-dialog
    v-model="updateDialogVisible"
    title="修改角色"
    width="500"
   
  >
    <!-- 修改角色页面-->
    <el-form v-model="updateRole">
      <el-form-item label="角色名称">
        <el-input v-model="updateRole.roleName" placeholder="请输入角色名称"/>
      </el-form-item>
      <el-form-item label="角色描述">
        <el-input v-model="updateRole.roleDes" placeholder="请输入角色描述"/>
      </el-form-item>
    </el-form>


    <template #footer>
      <div class="dialog-footer">
        <el-button @click="updateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateRoleBtn">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>



</template>

<script setup>
import { ref ,onMounted,reactive} from 'vue';
import { ElMessage, ElMessageBox, ElTree } from 'element-plus';
// 导入角色 js
import { getRoleList,saveRole ,findRoleById,updateRoleById,deleteById,deleteByRoleIds,findPermissonIds,assginPermission} from '../../api/sysRole'
// 导入权限 js
import { getTreeNodes } from '../../api/sysPermission'

// 角色数据
const roles = ref([
  
]);
// 新增角色控件显示、隐藏
const addDialogVisible = ref(false)
// 新增角色模型数据
let addRole = reactive({
  roleName:'',
  roleDes:''
})

// 修改控件的模型数据
let updateDialogVisible = ref(false)
let updateRole = ref({
  roleId:'',
  roleName:'',
  roleDes:''
})

// 权限树的数据（示例）
const permissionTreeData = ref([
  {
    id: 1,
    label: '系统管理',
    children: [
      { id: 2, label: '用户管理' },
      { id: 3, label: '角色管理' },
      { id: 4, label: '菜单管理' }
    ]
  },
  {
    id: 5,
    label: '订单管理',
    children: [
      { id: 6, label: '订单列表' },
      { id: 7, label: '订单详情' }
    ]
  }
]);

// 获取角色列表数据
const loadRoles = async () => {
  let  resp = await getRoleList()
  roles.value = resp.data
}




// 获取所有权限
const loadPermissionTree = async () => {
  let resp = await getTreeNodes()
  permissionTreeData.value = resp.data
}


// 新增角色
const addRoleBtn = async ()=>{
  try{
      let resp = await saveRole(addRole)
      ElMessage.success(resp.message)
      addDialogVisible.value = false
      clearModel()
      await loadRoles()
  }catch(err){
    ElMessage.error(err)
  }
}
// 修改角色
const updateRoleBtn = async() => {
  try{
    let resp =  await updateRoleById(updateRole.value)
    ElMessage.success(resp.message || "修改角色成功")
    updateDialogVisible.value = false
    // 重新加载当前页的数据
    loadRoles()
  }catch(err){
    ElMessage.error(err)
  }
}

const clearModel = () => {
  addRole = reactive({
    roleName:'',
    roleDes:''
  })
}


onMounted(()=>{
  // 加载角色
  loadRoles()
  // 加载权限
  loadPermissionTree()
})




// 当前编辑的角色 ID
const currentRoleId = ref(null);

// 控制抽屉是否显示
const assignPermissionDrawerVisible = ref(false);

// 树配置
const defaultProps = {
  children: 'children',
  label: 'label'
};

// el-tree 的引用
const treeRef = ref();



// 打开分配权限抽屉并加载已有权限
const openAssignPermissionDrawer = async(row) => {
  currentRoleId.value = row.roleId;
  // 这里可以调用 API 获取当前角色已有的权限，并设置为默认选中
  assignPermissionDrawerVisible.value = true;

  // 示例：设置默认选中项（你可以根据接口返回来设置）

  let resp = await findPermissonIds(row.roleId)
  treeRef.value.setCheckedKeys(resp.data)
  /*
  setTimeout(() => {
    // 假设你想默认选中 id=2 和 id=6 的权限
    treeRef.value.setCheckedKeys([2, 6]);
  }, 0);
  */
};

// 提交权限
const submitPermissions = async () => {
  const checkedKeys = treeRef.value.getCheckedKeys();
  //ElMessage.success(`角色 ${currentRoleId.value} 已保存权限：${checkedKeys.join(',')}`);
  let resp  = await assginPermission(currentRoleId.value,checkedKeys)
  ElMessage.success(resp.message || "权限设置成功")
  assignPermissionDrawerVisible.value = false;
};

// 其他方法省略（同上）...
const handleAddTag = () => { 
  addRole = reactive({
    roleName:'',
    roleDes:''
  })
  addDialogVisible.value = true
}
const handleEdit = async (rowId) => {
  const resp = await findRoleById(rowId)
  // 将数据交于模型数据
  updateRole.value = resp.data
  // 显示对话框
  updateDialogVisible.value = true
}
const handleDelete =  (id) => {
  ElMessageBox.confirm('确认删除该角色吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    //roles.value = roles.value.filter(r => r.roleId !== id);
    if(id){
      let resp = await deleteById(id)
      ElMessage.success(resp.message);
      await loadRoles()
    }
  });
};
// 批量删除
const handleBatchDelete = () => {
  if (!selectedIds.value.length) {
    ElMessage.warning('请至少选择一条记录');
    return;
  }

  ElMessageBox.confirm(`确认删除选中的 ${selectedIds.value.length} 条角色吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    //roles.value = roles.value.filter(r => !selectedIds.value.includes(r.roleId));
    // 调用接口进行批量删除
    let resp = await deleteByRoleIds(selectedIds.value)
    selectedIds.value = [];
    ElMessage.success(resp.message || '批量删除成功');
    await loadRoles()
  });
};

// 选中行处理
const selectedIds = ref([]);

// 将选中行的编号交于 selectedIds
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.roleId);
};
</script>

<style scoped>
.assign-permission-content {
  padding: 20px;
}

.drawer-footer {
  margin-top: 20px;
  text-align: right;
}
.mb-4 {
  margin-bottom: 1rem;
}
</style>